#!/usr/bin/perl -w
#
#

use strict;
use Data::Dumper;

use Config::General;
use DBI;

my $maskfile = $ARGV[0] || '../data/masks';

my %conf = Config::General->new('../mtt.conf')->getall();
my $ci = $conf{'Model::DBIC'}->{connect_info};

my $dbh = DBI->connect(
	$ci->{dsn},
	$ci->{user},
	$ci->{password}
) || die DBI->errstr;
$dbh->do( $ci->{on_connect_do} );

my $sth = $dbh->prepare('INSERT INTO masks VALUES(?, ?)');

open(M, $maskfile) || die "Mask file not found: $!";

$dbh->{AutoCommit} = 0;
$dbh->{RaiseError} = 1;

eval {
	$dbh->do('DROP TABLE masks');
	$dbh->do('CREATE TABLE IF NOT EXISTS masks(mask varchar(13) PRIMARY KEY, descr varchar(128))');
	$dbh->do('DELETE FROM masks');

	my %m;
	while (<M>) {
		my ($mask, $descr) = /^\s*([\d,]+)\s*(.+)\s*$/;
		next unless $mask;

		$mask =~ s/,//g;
		next if $m{$mask}++;

		$sth->execute($mask, $descr);
	}

	$dbh->commit;

	my $masks = $dbh->selectrow_arrayref('SELECT count(*) FROM masks')->[0];
	print "Loaded $masks masks\n";
};

if ($@) {
	warn "Error: $@";
	eval {
		$dbh->rollback();
	};
	if ($@) {
		warn "$@";
	}
}

close(M);



